package com.wwlwxg.spring_security.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * 导入 druid-spring-boot-starter 就可以直接在配置文件中去配置就可以了
 */
//@Configuration
public class MyDataSourceConfig {

  // 默认的自动配置是 @ConditionalOnMissingBean(DataSource.class) Hirika
  @ConfigurationProperties("spring.datasource")
  @Bean
  public DataSource dataSource() throws SQLException {
    DruidDataSource druidDataSource = new DruidDataSource();
    // 加入监控功能 （sql监控）
    druidDataSource.setFilters("stat,wall");

    return druidDataSource;
  }

  /**
   * 配置 druid 的sql监控页功能, url/druid
   * @return
   */
  @Bean
  public ServletRegistrationBean statViewServlet() {
    StatViewServlet statViewServlet = new StatViewServlet();
    ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");

    registrationBean.addInitParameter("loginUsername", "admin");
    registrationBean.addInitParameter("loginPassword", "123456");
    return registrationBean;
  }

  /**
   * WebStatFilter 用于采集 web-jdbc 关联监控的数据, (web应用)
   */
  @Bean
  public FilterRegistrationBean webStatFilter() {
    WebStatFilter statFilter = new WebStatFilter();

    FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>(statFilter);
    registrationBean.setUrlPatterns(Arrays.asList("/*"));
    registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

    return registrationBean;
  }
}
